package com.moon;

import java.util.ArrayList;
import java.util.Set;

import cn.yueliangbaba.R;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.RequestParams;
import com.moon.FragmentDynamic.MyAdapter.FoodHolder;
import com.sys.DemoApp;
import com.util.ImageLoaderHelper;
import com.util.MgqDataHandler;
import com.util.MgqRestClient;
import com.util.PreferencesUtils;
import com.util.ToastUtil;
import com.util.Utils;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class UserDisActivity extends BaseActivity {
	MyAdapter mAdapter;
	ArrayList<JSONObject> mArrayList = new ArrayList<JSONObject>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_dis);

		((TextView) findViewById(R.id.center)).setText("空间详情");
		findViewById(R.id.left).setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});

		
		final PullToRefreshListView ptrlvHeadlineNews = (PullToRefreshListView) findViewById(R.id.listview);
		ptrlvHeadlineNews.setMode(com.handmark.pulltorefresh.library.PullToRefreshBase.Mode.BOTH);
		ptrlvHeadlineNews.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() 
		{
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) 
			{
				sendRequest(false);
			}
		});
		
		ListView listview = ptrlvHeadlineNews.getRefreshableView();
		listview.setVerticalScrollBarEnabled(false);
		mAdapter = new MyAdapter();
		listview.setAdapter(mAdapter);
		
		sendRequest(true);
    }  
	
	class MyAdapter extends BaseAdapter implements OnClickListener{
		public int getCount() {
			return mArrayList.size();
		}

		public Object getItem(int position) {
			return null;
		}

		public long getItemId(int position) {
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			FoodHolder foodHold = null;

			if (convertView == null) {
				LayoutInflater mInflater = (LayoutInflater) UserDisActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				foodHold = new FoodHolder();

				convertView = mInflater.inflate(R.layout.item_main, null);
				
				foodHold.icon = (ImageView)convertView.findViewById(R.id.icon);
				foodHold.date = (TextView)convertView.findViewById(R.id.date);
				foodHold.time = (TextView)convertView.findViewById(R.id.time);
				foodHold.name = (TextView)convertView.findViewById(R.id.name);
				foodHold.classname = (TextView)convertView.findViewById(R.id.classname);
				foodHold.content = (TextView)convertView.findViewById(R.id.content);
				foodHold.sign = (TextView)convertView.findViewById(R.id.sign);

				foodHold.img0 = (ImageView)convertView.findViewById(R.id.img0);
				foodHold.img1 = (ImageView)convertView.findViewById(R.id.img1);
				foodHold.img2 = (ImageView)convertView.findViewById(R.id.img2);
				foodHold.img3 = (ImageView)convertView.findViewById(R.id.img3);
				foodHold.img4 = (ImageView)convertView.findViewById(R.id.img4);
				foodHold.img5 = (ImageView)convertView.findViewById(R.id.img5);
				foodHold.img6 = (ImageView)convertView.findViewById(R.id.img6);
				foodHold.img7 = (ImageView)convertView.findViewById(R.id.img7);
				foodHold.img8 = (ImageView)convertView.findViewById(R.id.img8);
				foodHold.arrow = (ImageView)convertView.findViewById(R.id.arrow);

				foodHold.comment0 = (TextView)convertView.findViewById(R.id.comment0);
				foodHold.comment1 = (TextView)convertView.findViewById(R.id.comment1);
				foodHold.comment2 = (TextView)convertView.findViewById(R.id.comment2);

				foodHold.praise = (TextView)convertView.findViewById(R.id.praise);
				foodHold.comment = (TextView)convertView.findViewById(R.id.comment);
				foodHold.line = (View)convertView.findViewById(R.id.line);
				
				convertView.setTag(foodHold);
			} else {
				foodHold = (FoodHolder) convertView.getTag();
			}
			
			JSONObject item = mArrayList.get(position);
			foodHold.pos = position;
			
			foodHold.sign.setVisibility(View.GONE);
			if(item.getInteger("is_teacher") == 1)
				foodHold.sign.setVisibility(View.VISIBLE);
			
			String path = item.getString("avatar_path");
			if(path != null && path.length() != 0) path = "http://120.27.129.233/ylbb/" + path;
			else path = "";
			if(item.getInteger("is_teacher") == 0)
				ImageLoaderHelper.displayImage(R.drawable.ic_family, foodHold.icon,path);
			else 
				ImageLoaderHelper.displayImage(R.drawable.ic_teacher, foodHold.icon,path);
			
			String name = item.getString("creator_name");
			if(item.getString("creator_alias") != null && item.getString("creator_alias").length() > 0) name = item.getString("creator_alias");
			if(item.getString("creator").equals(PreferencesUtils.getString(UserDisActivity.this, "userId"))) name = "我";
			foodHold.name.setText(name);
			foodHold.content.setText(item.getString("title") + "\n" + item.getString("content"));
			
			name = item.getString("class_name");
			if(item.getString("class_name_alias") != null && item.getString("class_name_alias").length() > 0) name = item.getString("class_name_alias");
			foodHold.classname.setText(name);

			foodHold.time.setText(Utils.getDateStr(item.getString("created_at")));
			foodHold.date.setText(getType(item.getIntValue("type")));
			
			foodHold.img0.setVisibility(View.GONE);
			foodHold.img1.setVisibility(View.GONE);
			foodHold.img2.setVisibility(View.GONE);
			foodHold.img3.setVisibility(View.GONE);
			foodHold.img4.setVisibility(View.GONE);
			foodHold.img5.setVisibility(View.GONE);
			foodHold.img6.setVisibility(View.GONE);
			foodHold.img7.setVisibility(View.GONE);
			foodHold.img8.setVisibility(View.GONE);
			
			foodHold.comment0.setVisibility(View.GONE);
			foodHold.comment1.setVisibility(View.GONE);
			foodHold.comment2.setVisibility(View.GONE);

			foodHold.praise.setVisibility(View.GONE);
			foodHold.comment.setVisibility(View.GONE);
			foodHold.line.setVisibility(View.GONE);
			
			foodHold.comment0.setOnClickListener(this);
			foodHold.comment1.setOnClickListener(this);
			foodHold.comment2.setOnClickListener(this);
			
			foodHold.comment0.setTag(Integer.valueOf(position));
			foodHold.comment1.setTag(Integer.valueOf(position));
			foodHold.comment2.setTag(Integer.valueOf(position));
			
			if(item.getInteger("receipt") == 1 && item.getInteger("is_feedbacked") == 0) foodHold.comment2.setVisibility(View.VISIBLE);
			if(item.getInteger("type") == 4)
			{
				if(item.getInteger("is_praised") == 0) foodHold.comment0.setVisibility(View.VISIBLE);
				foodHold.comment1.setVisibility(View.VISIBLE);
			}
			
			String img = item.getString("attach_list");
			if(img != null && img.length() > 0)
			{
				String[] imgs = img.split(",");
				int count = imgs.length;
				for(int i = 0;i < count; i++)
				{
					ImageView pImg = null;
					if(i == 0) pImg = foodHold.img0;
					else if(i == 1) pImg = foodHold.img1;
					else if(i == 2) pImg = foodHold.img2;
					else if(i == 3) pImg = foodHold.img3;
					else if(i == 4) pImg = foodHold.img4;
					else if(i == 5) pImg = foodHold.img5;
					else if(i == 6) pImg = foodHold.img6;
					else if(i == 7) pImg = foodHold.img7;
					else if(i == 8) pImg = foodHold.img8;
					
					pImg.setVisibility(View.VISIBLE);
					ImageLoaderHelper.displayImage(0, pImg, "http://120.27.129.233/ylbb/api/" + imgs[i] + "&width=160&height=160");
					pImg.setOnClickListener(this);
					pImg.setTag(foodHold);
				}
			}
			
			foodHold.arrow.setVisibility(View.GONE);
			
			String praiseStr = item.getString("praiseStr");
			String commentStr = item.getString("commentStr");
			
			if(praiseStr.length() > 0 || commentStr.length() > 0)
			{
				foodHold.arrow.setVisibility(View.VISIBLE);
			}
			
			if(praiseStr.length() > 0 && commentStr.length() > 0) foodHold.line.setVisibility(View.VISIBLE);
			if(praiseStr.length() > 0)
			{
				foodHold.praise.setVisibility(View.VISIBLE);
				foodHold.praise.setText(praiseStr);
			}
			
			if(commentStr.length() > 0)
			{
				foodHold.comment.setVisibility(View.VISIBLE);
				foodHold.comment.setText(commentStr);
			}
			
			return convertView;
		}
		//{"id":"28","title":"234234","content":"34534","receipt":"0","type":"1","creator":"16","identity_id":null,
//		"created_at":"2015-12-21 21:57:48","creator_name":"家长1","class_name":"2010年小5年级1班","identity_label":null,
//		"attach_list":"static\/upload\/attach\/2015\/12\/ff55cfb50e55fd23034543a4215f2cc1.jpg","is_feedbacked":"0","is_praised":"0"}
		public final class FoodHolder {
			public ImageView icon;
			public TextView date;
			public TextView time;
			public TextView name;
			public TextView classname;
			public TextView content;
			public TextView sign;
			
			public ImageView img0;
			public ImageView img1;
			public ImageView img2;
			public ImageView img3;
			public ImageView img4;
			public ImageView img5;
			public ImageView img6;
			public ImageView img7;
			public ImageView img8;
			public ImageView arrow;
			
			public TextView comment0;
			public TextView comment1;
			public TextView comment2;
			
			public TextView praise;
			public View line;
			public TextView comment;
			
			public int pos;
		}
		
		String getType(int type)
		{
			switch(type)
			{
			case 1:return "  作业";
			case 2:case 3:return "  通知";
			case 4:return "  动态";
			case 5:return "  进校/离校";
			}
			
			return "";
		}

		@Override
		public void onClick(View arg0) {
			int viewId = arg0.getId();
			switch(viewId)
			{
			case R.id.comment0:
				sendPraiseRequest((Integer)arg0.getTag());
				break;

			case R.id.comment1:
				showQuerySearch((Integer)arg0.getTag());
				break;
			
			case R.id.comment2:
				sendFeedbackRequest((Integer)arg0.getTag());
				break;
				
			case R.id.img0:
			case R.id.img1:
			case R.id.img2:
			case R.id.img3:
			case R.id.img4:
			case R.id.img5:
			case R.id.img6:
			case R.id.img7:
			case R.id.img8:
				showImage((FoodHolder)arg0.getTag(),viewId);
				break;
			}
		}
		
		void showImage(FoodHolder foodHolder,int viewId)
		{
			((DemoApp)getApplicationContext()).cleanBitmap();
			
			JSONObject item = mArrayList.get(foodHolder.pos);
			int index = viewId - R.id.img0;

			Intent intent = new Intent(UserDisActivity.this,ImageShowActivity.class);
			String[] array = item.getString("attach_list").split(",");
			for(int i = 0; i < array.length; i++)
			{
				ImageView imageview = null;
				if(0 == i) imageview = foodHolder.img0;
				if(1 == i) imageview = foodHolder.img1;
				if(2 == i) imageview = foodHolder.img2;
				if(3 == i) imageview = foodHolder.img3;
				if(4 == i) imageview = foodHolder.img4;
				if(5 == i) imageview = foodHolder.img5;
				if(6 == i) imageview = foodHolder.img6;
				if(7 == i) imageview = foodHolder.img7;
				if(8 == i) imageview = foodHolder.img8;
				imageview.setDrawingCacheEnabled(true);
				Bitmap bitmap = imageview.getDrawingCache();
				
				((DemoApp)getApplicationContext()).mBitmapArray.add(bitmap);
			}
			
			intent.putExtra("imgs", item.getString("attach_list"));
			intent.putExtra("index", index);
			startActivity(intent);
		}
	}
	
	private void sendCommentkRequest(int postId,final String text) {
		final JSONObject item = mArrayList.get(postId);
		
		MgqDataHandler loginHandler = new MgqDataHandler(UserDisActivity.this, true, false) {
			@Override
			public void onSuccess(String response) {

				JSONObject ruser = JSON.parseObject(response);
				if (ruser.getString("statusCode").equals("0")) {
//					autoRefresh();
					
					String commentStr = item.getString("commentStr");
					JSONObject member = JSON.parseObject(PreferencesUtils.getString(UserDisActivity.this, "member"));
					if(commentStr.length() > 0) commentStr += "\n";
					commentStr += member.getString("username") + ": " + text;
					item.put("commentStr", commentStr);
					mAdapter.notifyDataSetChanged();
				}
				else 
				{
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			
			}
			
			@Override
			public void onFailure(Throwable ble) {
				super.onFailure(ble);
				ToastUtil.showToastWithAlertPic("网络状况不佳，请稍后重试...");
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("id", PreferencesUtils.getString(UserDisActivity.this, "userId"));
		params.put("post_id",  item.getIntValue("id"));
		params.put("comment", text);
		MgqRestClient.get("send_post_comment", params, loginHandler);
	}
	
	private void sendFeedbackRequest(int postId) {
		final JSONObject item = mArrayList.get(postId);
		
		MgqDataHandler loginHandler = new MgqDataHandler(UserDisActivity.this, true, false) {
			@Override
			public void onSuccess(String response) {

				JSONObject ruser = JSON.parseObject(response);
				if (ruser.getString("statusCode").equals("0")) {
//					autoRefresh();
					
					item.put("is_feedbacked", 1);
					mAdapter.notifyDataSetChanged();
				}
				else 
				{
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			
			}
			
			@Override
			public void onFailure(Throwable ble) {
				super.onFailure(ble);
				ToastUtil.showToastWithAlertPic("网络状况不佳，请稍后重试...");
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("id", PreferencesUtils.getString(UserDisActivity.this, "userId"));
		params.put("post_id", item.getIntValue("id"));
		MgqRestClient.get("send_post_feedback", params, loginHandler);
	}
	
	private void sendPraiseRequest(int postId) {
		final JSONObject item = mArrayList.get(postId);
		
		MgqDataHandler loginHandler = new MgqDataHandler(UserDisActivity.this, true, false) {
			@Override
			public void onSuccess(String response) {

				JSONObject ruser = JSON.parseObject(response);
				if (ruser.getString("statusCode").equals("0")) {
//					autoRefresh();
					String praiseStr = item.getString("praiseStr");
					JSONObject member = JSON.parseObject(PreferencesUtils.getString(UserDisActivity.this, "member"));
					if(praiseStr.length() > 0) praiseStr += ",";
					praiseStr += "我";
					item.put("is_praised", 1);
					item.put("praiseStr", praiseStr);
					mAdapter.notifyDataSetChanged();
				}
				else 
				{
					ToastUtil.showToastWithAlertPic(ruser.getString("message"));
				}
			
			}
			
			@Override
			public void onFailure(Throwable ble) {
				super.onFailure(ble);
				ToastUtil.showToastWithAlertPic("网络状况不佳，请稍后重试...");
			}
		};
		
		RequestParams params = new RequestParams();
		params.put("id", PreferencesUtils.getString(UserDisActivity.this, "userId"));
		params.put("post_id", item.getIntValue("id"));
		MgqRestClient.get("send_post_praise", params, loginHandler);
	}
	
	void removeClassId(Integer classId)
	{
		for(Integer id : ((DemoApp)UserDisActivity.this.getApplicationContext()).mClassesSelected)
		{
			if(id.intValue() == classId.intValue())
			{
				((DemoApp)UserDisActivity.this.getApplicationContext()).mClassesSelected.remove(id);
				break;
			}
		}
	}
	
	boolean isClass(Integer classId)
	{
		for(Integer id : ((DemoApp)UserDisActivity.this.getApplicationContext()).mClassesSelected)
		{
			if(id.intValue() == classId.intValue())
			{
				return true;
			}
		}
		
		return false;
	}
	
	void showQuerySearch(final int postId) {
		final Dialog mDialog = new Dialog(UserDisActivity.this, R.style.Dialog_Fullscreen);
		mDialog.setContentView(R.layout.dialog_input);
		mDialog.findViewById(R.id.layout).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						mDialog.dismiss();
					}
				});
		mDialog.findViewById(R.id.btn1).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						String text = ((EditText)mDialog.findViewById(R.id.content)).getText().toString();
						if(text.length() == 0)
						{
							ToastUtil.showToastWithAlertPic("请输入内容");
							return;
						}
						
						sendCommentkRequest(postId,text);
						mDialog.dismiss();
					}
				});
		mDialog.show();
		
		((EditText)mDialog.findViewById(R.id.content)).setOnEditorActionListener(new OnEditorActionListener(){

			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				return true;
			}
		}); 
	}
	
	public void autoRefresh()
	{
		mArrayList.removeAll(mArrayList);
		mAdapter.notifyDataSetChanged();
		sendRequest(false);
	}
	
	private void sendRequest(boolean show) {
		MgqDataHandler loginHandler = new MgqDataHandler(UserDisActivity.this, show, false) {
			@Override
			public void onSuccess(String response) {
				JSONObject ruser = JSON.parseObject(response);
				JSONArray member = ruser.getJSONArray("datalist");
				for(int i = 0; i < member.size(); i++)
				{
					JSONObject item = member.getJSONObject(i);
					
					StringBuffer praise = new StringBuffer();
					StringBuffer comments = new StringBuffer();
					
					JSONArray pArray = item.getJSONArray("praise");
					JSONArray cArray = item.getJSONArray("comment");
					
					for(int j = 0; j < pArray.size();j++)
					{
						if(j > 0) praise.append(",");
						praise.append(pArray.getJSONObject(j).getString("username"));
					}
					
					for(int j = 0; j < cArray.size();j++)
					{
						if(j > 0) comments.append("\n");
						comments.append(cArray.getJSONObject(j).getString("username") + ": " + cArray.getJSONObject(j).getString("comment"));
					}
					
					item.put("praiseStr", praise.toString());
					item.put("commentStr", comments.toString());
					mArrayList.add(item);
				}
				
				mAdapter.notifyDataSetChanged();
				((PullToRefreshListView) findViewById(R.id.listview)).onRefreshComplete();
			}
			
			@Override
			public void onFailure(Throwable ble) {
				super.onFailure(ble);
				((PullToRefreshListView) findViewById(R.id.listview)).onRefreshComplete();
				ToastUtil.showToastWithAlertPic("网络状况不佳，请稍后重试...");
			}
		};
		/*
		String classIds = "";
		JSONObject array = ((DemoApp)this.getApplicationContext()).mClasses;
		Set<String> keys = array.keySet();
		for(String key : keys)
		{
			if(classIds.length() > 0) classIds += ",";
			classIds += key;
		}
		*/
		RequestParams params = new RequestParams();
		params.put("id", getIntent().getStringExtra("userId"));
//		params.put("class_id", classIds);
		params.put("type", 4);
		params.put("start", mArrayList.size());
		params.put("perpage", 10);
		MgqRestClient.get("get_my_post_list", params, loginHandler);
	}

}
